package com.apes.autoparts.supplier.platform;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.supplier.contrast.ContrastDao;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.query.QueryService;
import com.apes.framework.query.SqlService;
import com.apes.framework.util.DistributedLock;
import com.apes.framework.util.MapUtil;
import com.apestech.framework.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("supplierPlatformService")
public class SupplierPlatformService extends DomainService {
    @Autowired
    private SupplierPlatformItemRepository supplierPlatformItemRepository;
    @Autowired
    private SupplierPlatformRepository supplierPlatformRepository;
    @Autowired
    private ContrastDao contrastDao;
    @Autowired
    private DistributedLock distributedLock;
    @Autowired
    SqlService sqlService;
    /***
     * 同步所有数据
     */
    public void synTotal(SimpleRequest request) {
        SupplierPlatformItem supplierPlatformItem = supplierPlatformItemRepository.findOne((String)request.get("id"));
        if ("".equals(supplierPlatformItem.getState())) return;
            SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                supplierPlatformItem.getSupplierPlatform().getCode());
        supplierPlatformApi.synTotal(supplierPlatformItem);
    }

    /***
     * 同步增量数据
     */
    public void synIncrement(SimpleRequest request) {
        SupplierPlatformItem supplierPlatformItem = supplierPlatformItemRepository.findOne((String)request.get("id"));
        if ("debugging".equals(supplierPlatformItem.getState())) return;
        SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                supplierPlatformItem.getSupplierPlatform().getCode());
        supplierPlatformApi.synIncrement(supplierPlatformItem);
    }


    /***
     * 处理某一行数据
     */
    public void handleRow(SimpleRequest request) {
        JSONObject param = request.getJO();
        SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                param.getString("code"));
        supplierPlatformApi.handleRow(request);
    }

    /***
     * 模拟接口
     */
    public void simulationApi(SimpleRequest request) {
        SupplierPlatformItem supplierPlatformItem = supplierPlatformItemRepository.findOne((String)request.get("id"));
        SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                supplierPlatformItem.getSupplierPlatform().getCode());
        supplierPlatformApi.simulationApi(supplierPlatformItem, request.getJO());
    }

    /**
     * 同步多个供应商增量数据
     */
    public List<Map> synSuppliersIncrement(SimpleRequest request) {
        List<SupplierPlatformItem> supplierPlatformItems = supplierPlatformItemRepository.findAll();

        List<Map> list = supplierPlatformItems.stream().map(todo -> {
            return MapUtil.mapper(
                    "id", todo.getId()
            );
        }).collect(Collectors.toList());
        return list;
    }

    public List<Map> synSuppliersTotal(SimpleRequest request) {
        List<SupplierPlatformItem> supplierPlatformItems = supplierPlatformItemRepository.findAll();
        List<Map> list = supplierPlatformItems.stream().map(todo -> {
            return MapUtil.mapper(
                    "id", todo.getId()
            );
        }).collect(Collectors.toList());
        return list;
    }

    public Map getRowData(SimpleRequest request) {
        JSONObject object = request.getJO().getJSONObject("node");
        SupplierPlatformItem supplierPlatformItem = supplierPlatformItemRepository.findOne(object.getString("ITEM_ID"));
        SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                supplierPlatformItem.getSupplierPlatform().getCode());
        List<Map> rowData = supplierPlatformApi.getRowData(supplierPlatformItem, object.getString("SOURCE"));
        return rowData.size()> 0 ? rowData.get(0) : new HashMap();
    }

//    public Map OnlineSupplierData(SimpleRequest request) {
//
//    }

    public SupplierPlatform save(SimpleRequest request) {
        SupplierPlatform supplierPlatform = request.getO(SupplierPlatform.class);
        for (SupplierPlatformItem supplierPlatformItem : supplierPlatform.getSupplierPlatformItems()) {
            if (supplierPlatformItem.getState() == null || "".equals(supplierPlatformItem.getState()) ) supplierPlatformItem.setState("normal");
        }
        return supplierPlatformRepository.saveAndFlush(supplierPlatform);
    }

    public String delete(SimpleRequest request) {
        supplierPlatformRepository.delete(request.getO(SupplierPlatform.class));
        return "删除成功";
    }
    public JSONObject getOnlineData(SimpleRequest request) {
        JSONObject object = request.getJO().getJSONObject("node");
        JSONArray oneBusinessInfo = contrastDao.findOneBUSINESSINFOBySource(MapUtil.mapper(
                "SUPPLIER_PLATFORM_ITEM_ID", object.getString("ITEM_ID"),
                "SUPPLIER_PLATFORM_SOURCE", object.getString("SOURCE"),
                "SUPPLIER_ID", object.getString("ORIGIN")
        ));
        return oneBusinessInfo.size()> 0 ? oneBusinessInfo.getJSONObject(0) : new JSONObject();
    }

    public void debugging(SimpleRequest request) {
        SupplierPlatformItem supplierPlatformItem = supplierPlatformItemRepository.findOne((String)request.get("id"));
        SupplierPlatformApi supplierPlatformApi = SupplierPlatformUtil.getBusinessExecutor(SupplierPlatformApi.class,
                supplierPlatformItem.getSupplierPlatform().getCode());
        supplierPlatformApi.synIncrement(supplierPlatformItem);
    }

    public void synTotalTask(SimpleRequest request) {
        String code = request.getJO().getString("code");
        List<SupplierPlatform> supplierPlatformList = supplierPlatformRepository.findByCode(code);
        for (SupplierPlatformItem item : supplierPlatformList.get(0).getSupplierPlatformItems()) {
            MQUtil.publish("auto.supplierPlatform.synTotal", "同步平台全量数据", MapUtil.mapper("id", item.getId()));
        }
    }

    public void synIncrementTask(SimpleRequest request) {
        String code = request.getJO().getString("code");
        List<SupplierPlatform> supplierPlatformList = supplierPlatformRepository.findByCode(code);
        for (SupplierPlatformItem item : supplierPlatformList.get(0).getSupplierPlatformItems()) {
        MQUtil.publish("auto.supplierPlatform.synIncrement", "同步平台增量数据", MapUtil.mapper("id", item.getId()));
        }
    }

    // 同步一个供应商全量数据（前端调用）
    public String getSynTotal(SimpleRequest request) throws InterruptedException {
        String lockId = "supplierApi" + request.getJO().getString("id");
        if(!distributedLock.lock(lockId, 30 * 60 * 1000)) {
            throw new RuntimeException("后台正在调用第三方接口，请稍后再试");
        }
        try {
            this.synTotal(request);

        } catch (Exception e) {
            distributedLock.unlock(("supplierApi" + request.getJO().getString("id")));
            throw new RuntimeException(e);
        }
        distributedLock.unlock(("supplierApi" + request.getJO().getString("id")));
        return "调用成功";
    }

}
